package com.cqndt.disaster.device.util;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author qingqinchao
 */
public class UZipFileUtil {
    public static String unZipFiles(File zipFile, String descDir) throws IOException {
        String url1 = null;
        String url2 = null;

        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        //解决zip文件中有中文目录或者中文文件
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
        for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            String[] split1 = zipEntryName.split("/");
            if (zipEntryName.endsWith("xml")) {
                url1 = zipEntryName;
            }
            if ("index.html".equals(split1[split1.length - 1])) {
                url2 = zipEntryName;
            }

            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
            //判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            //输出文件路径信息
            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        return null != url2 ? url2 : url1;

    }

    public static void main(String[] args) {
        String zipFilePath = "E:\\temp\\temp.zip";
        File file = new File(zipFilePath);
        String unzipFilePath = "E:\\temp\\zip\\";
        try {
            unZipFiles(file,unzipFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
